package com.xls.pet.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.mybatisflex.annotation.*;
import com.xls.pet.listener.ItemStockOnSetListener;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serial;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Date;
import java.time.LocalDateTime;

/**
 * 实体类。
 *
 * @author xls
 * @since 2024-06-17
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(value = "item_stock", onSet = ItemStockOnSetListener.class)
public class ItemStock implements Serializable {

    @Serial
    private static final long serialVersionUID = 1L;

    @Id(keyType = KeyType.Auto)
    private Integer id;

    private Integer itemId;

    /**
     * 原价
     */
    private BigDecimal price;

    /**
     * 购买价格
     */
    private BigDecimal purchasePrice;

    /**
     * 数量
     */
    private Integer quantity;

    /**
     * 重量
     */
    private String weight;

    /**
     * 生产日期
     */
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
    private Date productDate;

    /**
     * 过期时间
     */
    private Date expirationDate;

    /**
     * 剩余天数
     */
    @Column(ignore = true)
    private Integer remainingDays;

    /**
     * 剩余天数百分比=(过期时间-生产日期)/(当前日期-生产日期)
     */
    @Column(ignore = true)
    private Integer percentage;

    @Column(onInsertValue = "now()")
    private LocalDateTime createTime;

    @Column(onInsertValue = "now()", onUpdateValue = "now()")
    private LocalDateTime updateTime;

    @Column(ignore = true)
    private Integer stockAvailable;

    @RelationOneToOne(selfField = "id", targetField = "id")
    private Item item;

    @JsonIgnore
    public void calculateExpirationDate(Integer unit, Integer shelfLife) {
        if (unit == 1) {
            this.setExpirationDate(Date.valueOf(
                    this.getProductDate()
                            .toLocalDate()
                            .plusYears(shelfLife)));
        } else if (unit == 2) {
            this.setExpirationDate(Date.valueOf(
                    this.getProductDate()
                            .toLocalDate()
                            .plusMonths(shelfLife)));
        } else {
            this.setExpirationDate(Date.valueOf(
                    this.getProductDate()
                            .toLocalDate()
                            .plusDays(shelfLife)));
        }
    }
}
